

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="CodeHope">
  <meta name="author" content="CodeHope">
  <meta name="keywords" content="希望">
  <title>回首掏之JavaScript中的宏任务和微任务 - CodeHope</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      
        
          
          
          
        
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/themes/prism-tomorrow.min.css" />
      
      
        <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.22.0/plugins/line-numbers/prism-line-numbers.min.css" />
      
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"quancundexiwang.wang","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":true,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"onlypost":true},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz","app_key":"hMuhiD4FRqhns4giqLiEH9HG","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
  <header style="height: 80vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>CodeHope</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                村头
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                我
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('http://qiniuyun.quancundexiwang.wang/20210328164211.png') repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="回首掏之JavaScript中的宏任务和微任务">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-03-28 16:36" pubdate>
        2021年3月28日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      32
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">回首掏之JavaScript中的宏任务和微任务</h1>
            
            <div class="markdown-body">
              <h1 id="回首掏之JavaScript中的宏任务和微任务"><a href="#回首掏之JavaScript中的宏任务和微任务" class="headerlink" title="回首掏之JavaScript中的宏任务和微任务"></a>回首掏之JavaScript中的宏任务和微任务</h1><h2 id="1-关于主流的-Chrome-浏览器"><a href="#1-关于主流的-Chrome-浏览器" class="headerlink" title="1.关于主流的 Chrome 浏览器"></a>1.关于主流的 <strong>Chrome</strong> 浏览器</h2> <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【Chrome 采用多进程架构。】</p>

<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210327130452590.png" srcset="/img/loading.gif"></p>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210327131200720.png" srcset="/img/loading.gif" alt="image-20210327131200720"></p>
<p>每打开一个tab页，就相当于于创建了一个独立的浏览器进程，这一点从上面的图中可以看出，但是也不是绝对的，它也有自己的优化机制，有的进程可能会被合并。</p>
<h3 id="a-Chrome-的主要进程及其职责"><a href="#a-Chrome-的主要进程及其职责" class="headerlink" title="a).Chrome 的主要进程及其职责"></a><strong>a).<code>Chrome</code> 的主要进程及其职责</strong></h3><p><img src="http://qiniuyun.quancundexiwang.wang/image-20210328000645654.png" srcset="/img/loading.gif" alt="image-20210328000645654"></p>
<ul>
<li><strong>Browser Process</strong> 浏览器的主进程（负责协调、主控） <ul>
<li>（1）负责包括地址栏，书签栏，前进后退按钮等部分的工作 </li>
<li>（2）负责处理浏览器的一些不可见的底层操作，比如网络请求和文件访问 </li>
<li>（3）负责各个页面的管理，创建和销毁其他进程</li>
</ul>
</li>
<li><strong>Renderer Process</strong> 负责一个 tab 内关于网页呈现的所有事情，页面渲染，脚本执行，事件处理等</li>
<li><strong>Plugin Process</strong> 负责控制一个网页用到的所有插件，如 flash 每种类型的插件对应一个进程，仅当使用该插件时才创建</li>
<li><strong>GPU Process</strong> 负责处理 GPU (图形处理器)相关的任务</li>
</ul>
<h3 id="b-Chrome-多进程架构的优缺点"><a href="#b-Chrome-多进程架构的优缺点" class="headerlink" title="b).Chrome 多进程架构的优缺点"></a>b).<strong><code>Chrome</code> 多进程架构的优缺点</strong></h3><ul>
<li><strong>优点：</strong> <ul>
<li>（1）某一渲染进程出问题不会影响其他进程 </li>
<li>（2）更为安全，在系统层面上限定了不同进程的权限</li>
</ul>
</li>
<li><strong>缺点：</strong><ul>
<li>（1）由于不同进程间的内存不共享，不同进程的内存常常需要包含相同的内容。<strong>为了节省内存，Chrome 限制了最多的进程数，最大进程数量由设备的内存和 CPU 能力决定，当达到这一限制时，新打开的 Tab 会共用之前同一个站点的渲染进程。</strong></li>
</ul>
</li>
</ul>
<p style='color:#035766;background:#feb856;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【以 Broswer Process 为例，如果 Chrome 运行在强大的硬件上，它会分割不同的服务到不同的进程，这样 Chrome 整体的运行会更加稳定，但是如果 Chrome 运行在资源贫瘠的设备上，这些服务又会合并到同一个进程中运行，这样可以节省内存。】</p>

<h3 id="c-渲染进程中的多线程"><a href="#c-渲染进程中的多线程" class="headerlink" title="c).渲染进程中的多线程"></a>c).渲染进程中的多线程</h3><blockquote>
<p>对我们<code>FE</code>(前端开发者)来讲，最重要的是<code>Renderer Process</code>（渲染进程）下的多线程.</p>
</blockquote>
<blockquote>
<p>Chrome浏览器,默认为每个tab页面单独启用渲染进程，因此每个tab网页都有由其独立的渲染引擎实例.每个渲染进程又是多线程的，以下都是在渲染进程中进行的.</p>
</blockquote>
<p><img src="http://qiniuyun.quancundexiwang.wang/image-20210327214025237.png" srcset="/img/loading.gif"></p>
<ul>
<li><h4 id="GUI-渲染线程"><a href="#GUI-渲染线程" class="headerlink" title="GUI 渲染线程"></a>GUI 渲染线程</h4><blockquote>
<p>负责渲染浏览器界面HTML元素,当界面需要重绘(Repaint)或由于某种操作引发回流(reflow)时,该线程就会执行。在Javascript引擎运行脚本期间,GUI渲染线程都是处于挂起状态的,也就是说被”冻结”了.</p>
</blockquote>
</li>
<li><h4 id="JavaScript引擎线程-OnlyOne"><a href="#JavaScript引擎线程-OnlyOne" class="headerlink" title="JavaScript引擎线程(OnlyOne)"></a>JavaScript引擎线程(OnlyOne)</h4><blockquote>
<p>JS内核，<strong>负责处理Javascript脚本程序</strong>。 一直等待着任务队列中任务的到来，然后解析Javascript脚本，运行代码。<strong>一个Tab页（renderer进程）中无论什么时候都只有一个JS线程在运行JS程序。</strong>(单线程)</p>
</blockquote>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【ps：GUI渲染线程与JS引擎线程是互斥的，所以如果JS执行的时间过长，这样就会造成页面的渲染不连贯，导致页面渲染加载阻塞】</p>
</li>
<li><h4 id="定时触发器线程"><a href="#定时触发器线程" class="headerlink" title="定时触发器线程"></a>定时触发器线程</h4><blockquote>
<p>定时器<code>setInterval</code>与<code>setTimeout</code>所在线程浏览器定时计数器并不是由<code>JavaScript</code>引擎计数的 因为<code>JavaScript</code>引擎是单线程的,这个是浏览器单独开了个线程帮你计时，等时间到了再去通知<code>js</code>引擎。</p>
</blockquote>
</li>
<li><h4 id="事件触发线程"><a href="#事件触发线程" class="headerlink" title="事件触发线程"></a>事件触发线程</h4><ul>
<li>用来控制事件轮询，<code>JS</code>引擎自己忙不过来，需要浏览器另开线程协助</li>
<li>当<code>JS</code>引擎执行代码块如鼠标点击、<code>AJAX</code>异步请求等，会将对应任务添加到事件触发线程中</li>
<li>当对应的事件符合触发条件被触发时，该线程会把事件添加到待处理任务队列的队尾，等待JS引擎的处理</li>
<li>由于JS的单线程关系，所以这些待处理队列中的事件都得排队等待JS引擎处理（当JS引擎空闲时才会去执行）</li>
</ul>
</li>
<li><h4 id="异步http请求线程"><a href="#异步http请求线程" class="headerlink" title="异步http请求线程"></a>异步http请求线程</h4><p>在<code>XMLHttpRequest</code>在连接后是通过浏览器新开一个线程请求， 将检测到状态变更时，如果设置有回调函数，异步线程就产生状态变更事件放到 JavaScript引擎的处理队列中等待处理。</p>
</li>
</ul>
<h2 id="2-JavaScript引擎机制（单线程）"><a href="#2-JavaScript引擎机制（单线程）" class="headerlink" title="2.JavaScript引擎机制（单线程）"></a>2.JavaScript引擎机制（单线程）</h2><img src="http://qiniuyun.quancundexiwang.wang/u=1668836573,463527232&fm=26&gp=0.png?" srcset="/img/loading.gif" style="zoom:50%;" />

 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【JavaScript为什么是单线程】</p>

<p><code>Js</code>是单线程的，也就是说所有的代码是<strong>一行接着一行运行的</strong>，就是说<strong>同一个时间只能做一件事</strong>，那这样的话效率s是不是很低？</p>
<p>其实<code>javascript</code>的单线程特点是跟他的用途有关的。作为浏览器脚本语言，<code>JavaScript</code>的<strong>主要用途是与用户互动，以及操作DOM</strong>。假<strong>如不是单线程的话，在一个线程当我们在给某个DOM节点增加内容的时候，另一个线程正在删除这个DOM节点的内容</strong>，那就好像有点乱套？</p>
<p>当然我们可以通过<strong>锁</strong>来解决上面的问题。但为了避免因为引入了锁而带来更大的复杂性，Javascript在最初就选择了<strong>单线程执行</strong>。</p>
<p><strong>这也解释了为什么GUI线程和JS引擎是互斥的。</strong></p>
<p>当<code>JS</code>引擎执行时<code>GUI</code>线程会被挂起，<code>GUI</code>更新则会被保存在一个队 列中等到<code>JS</code>引擎线程空闲时立即被执行。</p>
<img src="http://qiniuyun.quancundexiwang.wang/src=http___fjmingfeng.com_img_0_5003913851_62_037179013df9104565e5c77658c0040e_5166392352_7398371113.jpg&refer=http___fjmingfeng.jpg" srcset="/img/loading.gif" style="zoom:67%;" />

<p><strong>那效率会不会真的很低呢？</strong><code>js</code>在处理任务的时候，<strong>所有任务只能在一个线程上排队被执行</strong>，那如果某一个任务耗时比较长呢？总不能等到它执行结束再去执行下一个，所以就引出了<strong>同步和异步</strong>的概念，解决了耗时操作导致js阻塞的问题。</p>
<p><strong>换句话说，在定义中不能 现在 立刻完成的任务将会异步执行</strong></p>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【同步和异步】</p>

<p>同步就是比如说我们去菜鸟驿站去取快递，现在需要身份码+你的快递盒上对应的二维码，一起扫码才能取快递，每一个人，都拿着自己的快递，自己的身份码，排队等前一个人把快递拿完，然后自己去取自己的快递，这个排队一个个的取快递的过程就叫做同步。</p>
<p>然后轮到你取快递，突然你手机的网络不行了，身份码没有办法使用，发现是你的电话欠费了，你又要去交电话费，又要从新打开APP获取新的身份码，这个是一个很耗时的操作，如果让后面的人等着你做完这一切步骤，显然是不太好的，那么你这个耗时的操作，就最好跑到其他地方去做，让后面的人继续取他们的快递。等你做完了那些，再去取快递，那么这样的操作叫做异步。</p>
<p style='color:#815abd;background:#fcdc01;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【当我们打开网站时，网页的渲染过程就是一大堆同步任务，比如页面骨架和页面元素的渲染。而像加载图片音乐之类占用资源大耗时久的任务，一般我们使用异步的方式处理，等他准备好了，再渲染到页面中！】</p>

<h2 id="3-剖析同步和异步的执行过程"><a href="#3-剖析同步和异步的执行过程" class="headerlink" title="3.剖析同步和异步的执行过程"></a>3.剖析同步和异步的执行过程</h2><p><img src="http://qiniuyun.quancundexiwang.wang/image-20210328112635114.png" srcset="/img/loading.gif"></p>
<p>用文字描述的话，大致是这样的:</p>
<ul>
<li>所有同步任务都在主线程上执行，形成一个执行栈 (Execution Context Stack)。</li>
<li>而异步任务会被放置到 Task Table，也就是上图中的异步处理模块，当异步任务有了运行结果，就将该函数移入任务队列。</li>
<li>一旦执行栈中的所有同步任务执行完毕，引擎就会读取任务队列，然后将任务队列中的第一个任务压入执行栈中运行。</li>
</ul>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>主线程不断重复第三步，也就是 只要主线程空了，就会去读取任务队列，该过程不断重复，<br/>这就是所谓的 【事件循环】。</p>

<h2 id="4-宏任务和微任务"><a href="#4-宏任务和微任务" class="headerlink" title="4.宏任务和微任务"></a>4.宏任务和微任务</h2><p>了解了上面的异步同步，事件循环以及任务队列的概念，那么我们就要聊一下异步中任务队列的小知识了！</p>
<p style='color:#035766;background:#feb856;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【宏任务和微任务都是对于耗时操作，阻塞单线程的解决方案！他们都是属于异步任务队列的任务】</p>

<p>既然他们都是异步的方案，那么他们的区别是上什么呢？</p>
<h3 id="4-1-宏任务的本质"><a href="#4-1-宏任务的本质" class="headerlink" title="4.1 宏任务的本质"></a>4.1 宏任务的本质</h3><blockquote>
<p>宏任务的本质就是：<strong>参与了事件循环的任务。</strong></p>
</blockquote>
<p>首先我们看一下常见的宏任务都有哪些？</p>
<table>
<thead>
<tr>
<th>#</th>
<th>浏览器</th>
<th>Node</th>
</tr>
</thead>
<tbody><tr>
<td><strong><code>I/O</code>操作</strong></td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td><strong><code>setTimeout</code></strong></td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td><strong><code>setInterval</code></strong></td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td><strong><code>setImmediate</code></strong></td>
<td>❌</td>
<td>✅</td>
</tr>
<tr>
<td><strong><code>requestAnimationFrame</code></strong></td>
<td>✅</td>
<td>❌</td>
</tr>
</tbody></table>
 <p style='color:#eaf1f8;background:#443da6;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【我们可以理解宏任务，是需要宿主环境支持的，】</p>

<p>比如你代码里写了个定时器<code>2s</code>之后执行一个操作,我们都知道<code>javascript</code>引擎是单线程的，所以这个计时操作，是不会让JavaScript引擎来操作，否则页面就会卡顿2s，显然是不行的，那么这个计时操作，就是由我们所在的宿主环境帮我们完成的，等计时一到，把对应的定时器回调函数放入我们的任务队列中我们再去调用！（这也是定时器不准的原因）</p>
<p><strong>（事件监听也算是一种宏任务，你单线程的JavaScript不可能一直监听着那么多dom元素，也是浏览器帮你做监听，然后当用户点击后，把对应的回调函数，放入队列中然后再去执行的）</strong></p>
<h3 id="4-2-微任务的本质"><a href="#4-2-微任务的本质" class="headerlink" title="4.2 微任务的本质"></a>4.2 微任务的本质</h3><blockquote>
<p>微任务的本质：<strong>直接在 Javscript 引擎中的执行的，没有参与事件循环的任务。</strong>是在当前脚本代码执行完后<strong>，立刻执行的</strong>，它并没有参与事件循环。</p>
<p>也可以说它是js层面的，宏任务是宿主层面的。</p>
</blockquote>
<p>常见的微任务：</p>
<table>
<thead>
<tr>
<th>#</th>
<th>浏览器</th>
<th>Node</th>
</tr>
</thead>
<tbody><tr>
<td><code>process.nextTick</code></td>
<td>❌</td>
<td>✅</td>
</tr>
<tr>
<td><code>MutationObserver</code></td>
<td>✅</td>
<td>❌</td>
</tr>
<tr>
<td><code>Promise.then catch finally</code></td>
<td>✅</td>
<td>✅</td>
</tr>
</tbody></table>
<p style='color:#035766;background:#feb856;padding:10px;font-weight:bolder;border-radius:15px;line-height:30px;'>【为什么同一任务代码中，微任务优先于宏任务执行呢？】</p>

<p>可以这么理解，我们可以把主线程其实也可以当作也队列，里面有一些同步任务，异步宏任务，异步微任务，异步宏任务是宿主帮我们完成一些耗时操作！然后通知JavaScript引擎去执行回调操作，微任务，算是JavaScript引擎内部的一些耗时操作，那么当我们同步的代码执行完成了，一些宏任务，我们的js引擎，不太确定，宿主（浏览器,node）帮我们做的事情，有没有做完，如果默认先执行宏任务的回调，而宿主又没有反应，那么JavaScript引擎还要等着宿主，显然是不太合理的，那么还不如我们的JavaScript引擎，先去执行自己可以控制的微任务，然后再去执行宏任务。这是我理解的为什么先执行微任务再去执行宏任务。</p>
<h2 id="看一些题"><a href="#看一些题" class="headerlink" title="看一些题"></a>看一些题</h2><div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js">console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'script start'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'setTimeout'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'promise1'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'promise2'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'script end'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<details style="padding:15px 10px;background:#2e339c;color:#f8fafc;transition:all .3s ease;border-radius:12px;">                <summary style="border:none;out-line:none">点击查看答案</summary>    
    <p>script start</p>
    <p>script end</p>
    <p>promise1</p>
    <p>promise2</p>
    <p>setTimeout</p>    
</details>

<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">async</span> <span class="token keyword">function</span> <span class="token function">async1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token function">async2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">async</span> <span class="token keyword">function</span> <span class="token function">async2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

<span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

<span class="token function">async1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<details style="padding:15px 10px;background:#2e339c;color:#f8fafc;transition:all .3s ease;border-radius:12px;">                <summary style="border:none;out-line:none">点击查看答案</summary>        <p>1</p>    <p>2</p>    <p>6</p>       <p>4</p>  <p>3</p>  <p>5</p> </details>

<div class="code-wrapper"><pre class="line-numbers language-js" data-language="js"><code class="language-js"><span class="token keyword">async</span> <span class="token keyword">function</span> <span class="token function">async1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
  <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token function">async2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">async</span> <span class="token keyword">function</span> <span class="token function">async2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token punctuation">&#123;</span>
      <span class="token function-variable function">then</span><span class="token operator">:</span><span class="token punctuation">(</span><span class="token parameter">res</span><span class="token punctuation">)</span><span class="token operator">=></span><span class="token punctuation">&#123;</span>
          console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token function">res</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

<span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>

<span class="token function">async1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></div>
<details style="padding:15px 10px;background:#2e339c;color:#f8fafc;transition:all .3s ease;border-radius:12px;">                <summary style="border:none;out-line:none">点击查看答案</summary>        
    <p>1</p>    
    <p>2</p>    
    <p>6</p>       
    <p>4</p>  
    <p>7</p>  
    <p>3</p>  
    <p>5</p> 
</details>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JavaScript%E5%9F%BA%E6%9C%AC%E5%8A%9F/">JavaScript基本功</a>
                    
                      <a class="hover-with-bg" href="/tags/es6%EF%BC%8C7%EF%BC%8C8%EF%BC%8C9%EF%BC%8C10/">es6，7，8，9，10..</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/posts/62797/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">MyBatis入门</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/posts/25539/">
                        <span class="hidden-mobile">Javascript中的`this,call,apply,bind`</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    Fluid.utils.waitElementVisible('vcomments', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "Mi65hxq7VAFUDwOLeIGAOgiV-gzGzoHsz",
          app_key: "hMuhiD4FRqhns4giqLiEH9HG",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the
    <a target="_blank" href="https://valine.js.org" rel="nofollow noopener noopener">comments powered by Valine.</a>
  </noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    

  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        豫ICP备20009912号-1
      </a>
    </span>
    
  </div>


  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":true,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    
      <script  src="/js/lazyload.js" ></script>
    
  



  
    
  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "http://qiniuyun.quancundexiwang.wang/xmlSearch.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
